package com.hubing.cloud.app.web.service.impl;

import com.google.common.collect.Lists;
import com.hubing.cloud.app.web.mapper.MenuMapper;
import com.hubing.cloud.app.web.mapper.NavigationMapper;
import com.hubing.cloud.app.web.model.dto.DocNavDto;
import com.hubing.cloud.app.web.model.entity.Navigation;
import com.hubing.cloud.app.web.model.entity.Search;
import com.hubing.cloud.app.web.service.NavigationService;
import com.hubing.cloud.app.web.model.bo.DocNavBO;
import com.hubing.cloud.app.web.model.vo.DocNavVO;
import com.hubing.cloud.app.web.util.IdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.lang.reflect.Array;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author 81517
* @description 针对表【navigation】的数据库操作Service实现
* @createDate 2023-01-31 01:42:54
*/
@Service
public class NavigationServiceImpl implements NavigationService {

    @Autowired
    private NavigationMapper navigationMapper;

    @Autowired
    private MenuMapper menuMapper;

    /**
     * 查询 - 文章导航
     *
     * @return
     */
    @Override
    public List<DocNavVO> queryNavigation() {
        Map<String, List<DocNavBO>> map = navigationMapper.queryDocnav().stream().collect(
                Collectors.toMap(DocNavBO::getRootMenuId, Lists::newArrayList,
                        (List<DocNavBO> l1, List<DocNavBO> l2) -> {
                            l2.addAll(l1);
                            return l2;
                        }));


        List<DocNavVO> list = new ArrayList<>();
        map.forEach((k,v) ->{
            DocNavVO vo = new DocNavVO();
            vo.setRootMenuId(k);
            vo.setRootMenuName(v.get(0).getRootMenuName());
            vo.setDocList(v);
            list.add(vo);
        });
        return list;
    }

    @Transactional
    @Override
    public Boolean saveNavigation(DocNavDto dto) {
        Date now = new Date();
        String rootMenuId = dto.getRootMenuId();
        List<String> docIds = Arrays.asList(dto.getDocIds().split(",")).stream().distinct().collect(Collectors.toList());

        Example example = new Example(Navigation.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("rootMenuId",rootMenuId);
        navigationMapper.deleteByExample(example);

        for(String docId: docIds) {
            Navigation navigation = new Navigation();
            navigation.setNavigationId(IdUtil.getIncreaseIdByCurrentTimeMillis());
            navigation.setDocId(docId);
            navigation.setRootMenuId(rootMenuId);
            navigation.setCreated(now);
            navigation.setVersion(1L);
        }
        return true;
    }
}
